<template>
  <div class="main-card">
    <el-card class="box-card">
      <template #header>
        <span>{{ title }}</span>
      </template>
      <el-form ref="ruleForm" :model="queryParams" label-width="100px">
        <div class="search-form">
          <el-form-item label="用户名">
            <el-input v-model="queryParams.username" clearable />
          </el-form-item>
          <el-form-item label="手机号码">
            <el-input v-model="queryParams.phoneNumber" clearable />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="queryParams.enable" clearable placeholder="请选择">
              <el-option
                label="正常"
                :value="1"
              />
              <el-option
                label="停用"
                :value="0"
              />
            </el-select>
          </el-form-item>
          <el-form-item prop="dateRange" label="操作时间">
            <el-date-picker
              v-model="queryParams.dateRange"
              clearable
              type="daterange"
              format="YYYY-MM-DD"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-form-item>
          <el-button style="margin-left: 20px" type="primary" @click="search">搜索</el-button>
        </div>
      </el-form>
      <div style="margin:20px 0;">
          <el-button v-hasPermi="['system:user:add']" type="primary" @click="addOrUpdate()">添加用户</el-button>
          <el-button v-hasPermi="['system:user:remove']" type="danger" @click="deleteUser">删除用户</el-button>
      </div>
      <div>
        <el-table
          :data="dataList"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
        <el-table-column
          type="selection"
          width="55"
        />
        <el-table-column
          prop="userId"
          label="用户编号"
          width="120"
        />
        <el-table-column
          prop="username"
          label="用户名称"
          width="120"
        />
        <el-table-column
          prop="nickName"
          label="用户昵称"
          width="120"
        />
        <el-table-column
          prop="phoneNumber"
          label="手机号码"
          width="120"
        />
        <el-table-column
          prop="enable"
          label="状态"
          width="120"
        >
          <template #default="{row}">
            <el-switch v-model="row.enable" @change="handleStatusChange(row)" />
          </template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="创建时间"
          width="120"
          :formatter="dateFormat"
        />
        <el-table-column label="操作" width="250">
          <template #default="{row}">
            <el-button v-hasPermi="['system:user:edit']" type="primary" @click="addOrUpdate(row)">修改</el-button>
            <el-button v-hasPermi="['system:user:resetPwd']" type="primary" @click="resetPassword(row)">重置</el-button>
            <el-button v-hasPermi="['system:user:remove']" type="danger" @click="deleteUser(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        v-show="total>0"
        :current-page="queryParams.pageNum"
        :page-size="queryParams.pageSize"
        :total="total"
        @current-change="handleCurrentChange"
      />
      </div>
    </el-card>
    <a-u-user
      v-model="isAuUserShow"
      @close="isAuUserShow = false"
      v-on:onRefresh="search"
    />
    <update-pwd
      :value="isUpdatePwdShow"
      @close="isUpdatePwdShow = false"
      v-on:onRefresh = "search"
    />
  </div>
</template>

<script lang="ts">
import { useRoute } from 'vue-router'
import { watchEffect, reactive, toRefs, defineComponent } from 'vue'
import { useStore } from 'vuex'
import AUUser from './components/AUUser.vue'
import UpdatePwd from './components/UpdatePwd.vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { StateType as UserStateType, User } from '@/store/modules/system/user'
import tableList, { BaseQueryType, BaseDataType } from '@/mixins/tableList'
import moment from 'moment'

interface QueryParamsType extends BaseQueryType{
  username: string;
  phoneNumber: string;
  dateRange: Array<string>;
  enable: number;
  startCreateTime: string;
  endCreateTime: string;
}

interface DataType extends BaseDataType<User> {
  isAuUserShow: boolean;
  isUpdatePwdShow: boolean;
  queryParams: QueryParamsType;
}

export default defineComponent({
  name: 'User',
  components: { AUUser, UpdatePwd },
  setup() {
    const route = useRoute()
    const title = route.meta.title
    const store = useStore<{user: UserStateType}>()
    const data = reactive<DataType>({
      url: 'user/getUserList',
      isAuUserShow: false,
      isUpdatePwdShow: false,
      dataList: [],
      queryParams: {
        username: '',
        phoneNumber: '',
        dateRange: [],
        enable: 1,
        startCreateTime: '',
        endCreateTime: '',
        pageNum: 1,
        pageSize: 10
      },
      total: 0,
      selectList: []
    })
    const {
      dateFormat,
      getList,
      handleSelectionChange,
      handleCurrentChange,
      search
    } = tableList(data)
    watchEffect(() => {
      if (data.queryParams.dateRange && data.queryParams.dateRange.length >= 2) {
        data.queryParams.startCreateTime = moment(data.queryParams.dateRange[0]).format('YYYY-MM-DD')
        data.queryParams.endCreateTime = moment(data.queryParams.dateRange[1]).format('YYYY-MM-DD')
      } else {
        data.queryParams.startCreateTime = ''
        data.queryParams.endCreateTime = ''
      }
    })
    // 修改添加账号
    const addOrUpdate = async (row: User) => {
      const userId = row ? row.userId : null
      await store.dispatch('user/getUser', userId)
      data.isAuUserShow = true
    }
    // 重置密码
    const resetPassword = (row: User) => {
      store.commit('user/SET_DATA', row)
      data.isUpdatePwdShow = true
    }
    // 删除
    const deleteUser = (row: User) => {
      const userIds = row.userId || ((data.selectList || []).map((item: User) => item.userId))
      ElMessageBox.confirm('您确定要删除"' + userIds + '"用户吗, 是否继续?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return store.dispatch('user/deleteUser', userIds)
      }).then(() => {
        ElMessage.success({ message: '删除成功', type: 'success' })
        getList.value()
      })
    }
    // 更改状态
    const handleStatusChange = (row: User) => {
      const text = row.enable ? '启用' : '停用'
      ElMessageBox.confirm('确认要' + text + '"' + row.username + '"用户吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return store.dispatch('user/changeStatus', row)
      }).then(() => {
        ElMessage({
          message: '更改状态成功',
          type: 'success'
        })
        getList.value()
      }).catch(() => {
        row.enable = !row.enable
      })
    }
    search.value()
    return {
      title,
      dateFormat,
      handleSelectionChange,
      handleCurrentChange,
      search,
      ...toRefs(data),
      resetPassword,
      addOrUpdate,
      deleteUser,
      handleStatusChange
    }
  }
})
</script>

<style lang="scss">
.el-pagination{
  margin-top: 20px;
}
</style>
